package com.ptszyxx.popose.module.main.dynamic.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.ptszyxx.popose.R;
import com.ysg.http.data.CommonRepository;
import com.ptszyxx.popose.common.event.ReplySuccessEvent;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YBusUtil;
import com.ysg.http.data.entity.dynamic.CommentEntity;
import com.ysg.http.data.entity.dynamic.CommentReplyEntity;
import com.ysg.http.data.entity.dynamic.DynamicResult;
import com.ysg.base.BaseViewModel;
import com.ysg.binding.command.BindingAction;
import com.ysg.binding.command.BindingCommand;
import com.ysg.bus.RxBus;
import com.ysg.bus.RxSubscriptions;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.http.BaseListResponse;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessListResult;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class DynamicCommentVM extends BaseViewModel<CommonRepository> {
    public int pageNo;
    public String dynamicId;
    public DynamicResult dynamicEntity;
    public CommentEntity currentCommentEntity;
    public int currentPosition;
    public int commentType = 1;//1.评论，2.回复评论
    public ObservableField<String> content = new ObservableField<>();

    public DynamicCommentVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }

    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent onRefreshEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onRefreshItemEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onHeaderEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onCommentEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onCommentCountEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onCommentClearEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onMoreEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onFollowEvent = new SingleLiveEvent<>();
    }

    public BindingCommand onSendCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestSendComment();
        }
    });
    public BindingCommand onLeftCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            YActivityUtil.getInstance().close(DynamicCommentVM.this);
        }
    });
    public BindingCommand onRightCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.onMoreEvent.call();
        }
    });

    public Disposable disposable;
    @Override
    public void registerRxBus() {
        super.registerRxBus();
        disposable = RxBus.getDefault().toObservable(ReplySuccessEvent.class)
                .subscribe(new Consumer<ReplySuccessEvent>() {
                    @Override
                    public void accept(ReplySuccessEvent event){
                        if (event != null){
                            requestCommentPage(true);
                        }
                    }
                });
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(disposable);
    }


    //=========================================接口：start===========================================
    /**
     * 动态
     */
    public void requestDynamic(){
        Map<String, String> map = new HashMap<>();
        map.put("dongtaiId", dynamicId);
        HttpUtils.getInstance()
                .data(model.dynamicDetail(map), this,
                        new OnSuccessResult<DynamicResult>() {
                            @Override
                            public void onSuccessResult(BaseResponse<DynamicResult> response) {
                                dynamicEntity = response.getData();
                                uc.onHeaderEvent.call();
                            }
                        });
    }
    /**
     * 动态删除
     */
    public void requestDynamicDelete(){
        Map<String, String> map = new HashMap<>();
        map.put("id", dynamicId);
        HttpUtils.getInstance()
                .data(model.dynamicDelete(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                YToastUtil.showShort(R.string.success_delete);
                                YActivityUtil.getInstance().close(DynamicCommentVM.this);
                                YBusUtil.dynamicDeleteSuccess();
                            }
                        });
    }

    /**
     * 评论列表
     */
    public void requestCommentPage(boolean refresh){
        if (refresh){
            pageNo = 1;
        }else{
            pageNo++;
        }
        Map<String, String> map = new HashMap<>();
        map.put("dongtaiId", dynamicId);
        map.put("pageNo", String.valueOf(pageNo));
        HttpUtils.getInstance()
                .list(model.dynamicCommentPage(map), this,
                        new OnSuccessListResult<CommentEntity>() {
                            @Override
                            public void onSuccessResult(BaseListResponse<CommentEntity> response) {
                                uc.onRefreshEvent.setValue(response.getData());
                            }
                        });
    }
    /**
     * 评论点赞
     */
    public void requestCommentLike(){
        String type;
        if (YStringUtil.eq(1, currentCommentEntity.getDzstate())){
            type = "2";
        }else{
            type = "1";
        }
        Map<String, String> map = new HashMap<>();
        map.put("commentid", currentCommentEntity.getId()+"");
        map.put("type", type);
        HttpUtils.getInstance()
                .data(model.dynamicCommentLike(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                if (YStringUtil.eq(1, currentCommentEntity.getDzstate())){
                                    currentCommentEntity.setDzstate(2);
                                    currentCommentEntity.setNum(currentCommentEntity.getNum() - 1);
                                }else{
                                    currentCommentEntity.setDzstate(1);
                                    currentCommentEntity.setNum(currentCommentEntity.getNum() + 1);
                                }
                                uc.onRefreshItemEvent.call();
                            }
                        });
    }
    /**
     * 发送评论
     */
    public void requestSendComment(){
        if (YStringUtil.isEmpty(content.get())){
            YToastUtil.showShort(R.string.dynamic_detail_comment_hint);
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("message", content.get());

        Observable observable;
        if (YStringUtil.eq(2, commentType)){
            map.put("commentid", currentCommentEntity.getId()+"");
            observable = model.dynamicCommentReply(map);
        }else{
            map.put("dongtaiId", dynamicId);
            observable = model.dynamicComment(map);
        }

        HttpUtils.getInstance()
                .data(observable, this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                if (YStringUtil.eq(2, commentType)){
                                    YToastUtil.showShort(R.string.success_reply);
                                    CommentReplyEntity replyEntity = new CommentReplyEntity();
                                    replyEntity.setHfnick(YSPUtils.getInstance().getUserName());
                                    replyEntity.setHfneirong(content.get());
                                    currentCommentEntity.getHfList().add(replyEntity);
                                    currentCommentEntity.setHfcount(currentCommentEntity.getHfcount() + 1);
                                    uc.onRefreshItemEvent.call();
                                }else{
                                    YToastUtil.showShort(R.string.success_comment);
                                    requestCommentPage(true);
                                    uc.onCommentCountEvent.call();
                                    YBusUtil.sendCommentSuccess();
                                }
                                uc.onCommentClearEvent.call();
                            }
                        });
    }

    /**
     * status:1为关注 2取消关注
     */
    public void requestFollow(){
        Integer status = 1;
        if (dynamicEntity == null){
            return;
        }
        if (YStringUtil.eq(1, dynamicEntity.getGuanzhuState())) {
            status = 2;
        } else if (YStringUtil.eq(2, dynamicEntity.getGuanzhuState())) {
            status = 1;
        }
        Map<String, String> map = new HashMap<>();
        map.put("userid", ""+dynamicEntity.getUserid());
        map.put("leixing", String.valueOf(status));

        Integer finalStatus = status;
        HttpUtils.getInstance()
                .data(model.follow(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                dynamicEntity.setGuanzhuState(finalStatus);
                                uc.onFollowEvent.call();
                            }
                        });
    }

    /**
     * 用户详情
     */
    public void jumpUserDetail(CommentEntity entity){
        YActivityUtil.getInstance().jumpUserDetail(DynamicCommentVM.this, entity.getUserid()+"");
    }
    /**
     * 动态评论回复
     */
    public void jumpDynamicReply(CommentEntity entity){
        YActivityUtil.getInstance().jumpDynamicReply(DynamicCommentVM.this, entity);
    }
    /**
     * 评论点赞
     */
    public void onCommentLikeClick(CommentEntity entity, int position){
        this.currentCommentEntity = entity;
        this.currentPosition = position;
        requestCommentLike();
    }
    /**
     * 回复
     */
    public void onReplyClick(CommentEntity entity, int position){
        this.currentCommentEntity = entity;
        this.currentPosition = position;
        this.commentType = 2;
        uc.onCommentEvent.call();
    }

}
